package com.df.ez_game.server.logic;

import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.df.ez_game.server.EzGameMsgCodecManager;
import com.df.ez_game.server.IEzGameMsgCodec;
import com.df.ez_game.server.msg.client.ClientReqMsg;
import com.df.ez_game.server.msg.client.ClientRespMsg;
import com.df.ez_game.tools.EzConstant;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

@Slf4j(topic = "client-codec")
public class WebsocketClientMsgCodec extends MessageToMessageCodec<BinaryWebSocketFrame, ClientRespMsg> {

    private Integer msgProtoType;
    WebsocketClientMsgCodec(Integer msgProtoType){
        this.msgProtoType = msgProtoType;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, ClientRespMsg respMsg, List<Object> out) throws Exception {
        /*
         *【游戏对外服】发送消息给【游戏客户端】
         * 编码器 - ExternalMessage ---> 字节数组，将消息发送到请求端（客户端）
         */
        IEzGameMsgCodec codec = EzGameMsgCodecManager.getCodec(this.msgProtoType);
        if(codec==null){
            throw new RuntimeException("没有对应的消息编解码器！消息类型："+this.msgProtoType);
        }
//        Codec<ClientRespMsg> codec = ProtobufProxy.create(ClientRespMsg.class);
        try {
            byte[] bytes = codec.encodeNetMsg(respMsg);
            // 使用默认 buffer 。如果没有做任何配置，通常默认实现为池化的 direct （直接内存，也称为堆外内存）
            ByteBuf byteBuf = ctx.alloc().buffer(bytes.length);
            byteBuf.writeBytes(bytes);
            BinaryWebSocketFrame socketFrame = new BinaryWebSocketFrame(byteBuf);
            out.add(socketFrame);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame o, List<Object> out) {
        ByteBuf contentBuf = o.content();
        byte[] msgBytes = new byte[contentBuf.readableBytes()];
        contentBuf.readBytes(msgBytes);
        IEzGameMsgCodec codec = EzGameMsgCodecManager.getCodec(this.msgProtoType);
        if(codec==null){
            throw new RuntimeException("没有对应的消息编解码器！消息类型："+this.msgProtoType);
        }
//        Codec<ClientReqMsg> codec = ProtobufProxy.create(ClientReqMsg.class);
        try {
            ClientReqMsg msg = codec.decodeNetMsg(msgBytes);
            out.add(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}